package zut.edu.cs.network.threads;

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.BlockingQueue; 
import java.util.concurrent.TimeUnit; 

public class InnerReader implements Runnable{
	/** 阻塞队列 */ 
	private BlockingQueue<List<String>> blockingQueue; 
	
	/** 输入文件名称 */ 
	private String inputFileName; 
	
	/** 队列最大长度 */ 
	private int maxQueueSize; 
	
	/** 一组数据大小 */ 
	private static final int GROUP_LIMIT = 1024; 
	
	/** 结束标识 */ 
	private static final List<String> END = new ArrayList<>(); 
	private static final Logger LOG = LoggerFactory.getLogger(InnerReader.class);

	public InnerReader() {
	}
	
	public InnerReader(BlockingQueue<List<String>> blockingQueue, String inputFileName, int maxQueueSize) {
		super();
		this.blockingQueue = blockingQueue;
		this.inputFileName = inputFileName;
		this.maxQueueSize = maxQueueSize;
	}

	@Override
	public void run() {
		File inputFile = new File(inputFileName);
		if (!inputFile.exists()) { 
			LOG.error("cat not find such file: {}", inputFileName); 
			return; 
		} 
		try { 
			BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile)); 
			String line; 
			List<String> dataGroup = new ArrayList<>(GROUP_LIMIT); 
			while ((line = bufferedReader.readLine()) != null) { 
				if (dataGroup.size() >= GROUP_LIMIT) { 
					addDataGroup(dataGroup); 
					// 数据重置 
					dataGroup = new ArrayList<>(GROUP_LIMIT); 
				} 
				dataGroup.add(line); 
			} 
			// 最后一批数据 
			addDataGroup(dataGroup);
			// 结束标识 
			addDataGroup(END); 
			bufferedReader.close(); 
			} catch (Exception e) { 
				LOG.error(e.getMessage()); 
			}
		}
		
	private void addDataGroup(List<String> dataGroup) throws Exception{ 
		while (blockingQueue.size() >= maxQueueSize) { 
			TimeUnit.SECONDS.sleep(3); 
		} 
		blockingQueue.add(dataGroup); 
	}
	
	
	
		

}
